import React, { useState, useEffect } from 'react'
import ReactECharts from 'echarts-for-react'
import * as echarts from 'echarts'
import BlockTitle from '../../../../../framework/BlockTitle'
import SouyeApi from '../../../../../../utils/apis/SouyeApi'

export default function Zfzhjznl() {
    const [chartData, setChartData] = useState([])
    const [loading, setLoading] = useState(true)
    const [total, setTotal] = useState(0)

    useEffect(() => {
        const fetchData = async () => {
            try {
                setLoading(true)
                const response = await SouyeApi.jzzy_find("政府综合减灾资源")
                if (response && response.data?.length) {
                    setChartData(response.data)
                    const totalCount = response.data.reduce((sum, item) => sum + item.count, 0)
                    setTotal(totalCount)
                } else {
                    const defaultData = [
                        { jzzyxl: '应急避难场所', count: 15 },
                        { jzzyxl: '救援队伍', count: 8 },
                        { jzzyxl: '应急物资储备', count: 12 },
                        { jzzyxl: '监测预警设备', count: 20 },
                        { jzzyxl: '应急指挥中心', count: 5 }
                    ]
                    setChartData(defaultData)
                    setTotal(60)
                }
            } catch (error) {
                console.error('获取政府综合减灾能力数据失败:', error)
                const defaultData = [
                    { jzzyxl: '应急避难场所', count: 15 },
                    { jzzyxl: '救援队伍', count: 8 },
                    { jzzyxl: '应急物资储备', count: 12 },
                    { jzzyxl: '监测预警设备', count: 20 },
                    { jzzyxl: '应急指挥中心', count: 5 }
                ]
                setChartData(defaultData)
                setTotal(60)
            } finally {
                setLoading(false)
            }
        }
        
        fetchData()
    }, [])

    const getOption = () => {
        if (!chartData || chartData.length === 0) {
            return {}
        }

        const colors = ['#4A9EFF', '#00E5A0', '#FFD700', '#FF6B9D', '#9B59B6'] // 多种颜色
        
        const pieData = chartData.map((item, index) => ({
            name: item.jzzyxl,
            value: item.count,
            itemStyle: {
                color: colors[index % colors.length]
            }
        }))

        return {
            backgroundColor: 'transparent',
            // title: {
            //     text: total.toString(),
            //     subtext: '总数（处）',
            //     left: 'center',
            //     top: 'center',
            //     textStyle: {
            //         fontSize: 28,
            //         fontWeight: 'bold',
            //         color: '#ffffff'
            //     },
            //     subtextStyle: {
            //         fontSize: 12,
            //         color: '#ffffff',
            //         lineHeight: 16
            //     }
            // },
            tooltip: {
                trigger: 'item',
                backgroundColor: 'rgba(0, 0, 0, 0.8)',
                borderColor: '#4A9EFF',
                borderWidth: 1,
                textStyle: {
                    color: '#ffffff'
                },
                formatter: function(params) {
                    const percent = ((params.value / total) * 100).toFixed(1)
                    return params.name + '：' + params.value + ' 处 (' + percent + '%)'
                }
            },
            legend: {
                orient: 'vertical',
                right: 10,
                top: 'center',
                textStyle: {
                    color: '#ffffff',
                    fontSize: 11,
                    lineHeight: 16
                },
                itemWidth: 8,
                itemHeight: 8,
                formatter: function(name) {
                    const item = chartData.find(d => d.jzzyxl === name)
                    const count = item ? item.count : 0
                    // 长文本换行显示
                    let displayName = name
                    if (name.length > 6) {
                        displayName = name.slice(0, 6) + '\n' + name.slice(6)
                    }
                    return displayName + ' ' + count
                }
            },
            series: [{
                type: 'pie',
                radius: ['35%', '55%'], // 圆环形饼图
                center: ['32%', '50%'], // 更靠左，为图例留更多空间
                avoidLabelOverlap: false,
                label: {
                    show: false // 不显示标签，避免拥挤
                },
                labelLine: {
                    show: false
                },
                emphasis: {
                    scale: true,
                    scaleSize: 3
                },
                data: pieData
            }]
        }
    }

    return (
        <div className='fill layout-v' style={{
            width: '100%',
            overflow: 'hidden'
        }}>
            <BlockTitle style={{
                marginBottom: 0,
                fontFamily: 'pmzd'
            }}>
                政府综合减灾资源
            </BlockTitle>
            
            <div className='fill' style={{
                padding: '10px'
            }}>
                {loading ? (
                    <div style={{
                        display: 'flex',
                        justifyContent: 'center',
                        alignItems: 'center',
                        height: '100%',
                        color: '#ffffff',
                        fontSize: '14px'
                    }}>
                        数据加载中...
                    </div>
                ) : (
                    <ReactECharts 
                        option={getOption()} 
                        style={{ height: '100%', width: '100%' }}
                        notMerge={true}
                        lazyUpdate={true}
                    />
                )}
            </div>
        </div>
    )
} 